﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace WindowsGame5 {
    public class Missile {
        public Vector3 Direction { get; set; }
        public Vector3 Position { get; set; }
        public Vector3 Up { get; set; }
        public Vector3 Right { get; set; }
        public Boolean Active { get; set; }
        public Model Model { get; set; }
        public float Speed { get; set; }
        public float Scale { get; set; }

        private ParticleSystem trailParticles;
        private ParticleSystem explosionParticles;
        private Vector3 positionOffset;
        private int numExplosionParticles = 50;

        public Missile(Model missileModel, float scale, 
            ParticleSystem _trailParticles, ParticleSystem _explosionParticles) {
            this.Model = missileModel;
            this.Scale = scale;
            this.trailParticles = _trailParticles;
            this.explosionParticles = _explosionParticles;
            this.positionOffset = new Vector3(0.0f, 50.0f, 0.0f);
        }

        public void activate(Vector3 pos, Vector3 dir, float speed) {
            this.Position = pos;
            this.Direction = dir;
            this.Right = Vector3.Cross(this.Direction, Vector3.Up);
            this.Up = Vector3.Cross(this.Right, this.Direction);
            this.Speed = speed;
            this.Active = true;

            this.Direction.Normalize();
            this.Right.Normalize();
            this.Up.Normalize();
        }
        public void Update(float elapsedTime, BoundingBox worldBound, HeightMapInfo heightMap) {
            if (this.Active == false)
                return;

            Vector3 previousPosition = this.Position;
            Vector3 velocity = this.Direction * this.Speed;
            this.Position += velocity * elapsedTime;
            if (worldBound.Contains(this.Position) == ContainmentType.Disjoint
                || heightMap.GetHeight(this.Position) > this.Position.Y) {
                for (int i = 0; i < numExplosionParticles; i++)
                    this.explosionParticles.AddParticle(
                         previousPosition, Vector3.Up);
                this.Active = false;
                return;
            }

            this.trailParticles.AddParticle(this.Position, velocity / 2);
        }
        public Matrix getTransformation() {
            Matrix rotationMatrix = Matrix.Identity;
            rotationMatrix.Forward = this.Direction;
            rotationMatrix.Right = this.Right;
            rotationMatrix.Up = this.Up;

            return Matrix.CreateScale(this.Scale)
                * rotationMatrix
                * Matrix.CreateTranslation(this.Position);
        }
    }
}
